﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CochinitaCorte
{
    public partial class UsersManager : Form
    {
        private enum ItemRights
        {
            Administrador = 2,
            Catalogos = 4,
            Caja = 8,
            Reportes = 16,
            Comunicados = 32,
            FullAccess = 62,
        }

        private string UserRights = string.Empty;

        private BusinessLayer BL = new BusinessLayer();
       
        private IEnumerable<object> UserInfo;

        private bool NewUSer = false;
        
        private void GetID()
        {
           txtID.Text = BL.GetMaxUserID().ToString();
        }

        public UsersManager()
        {
            InitializeComponent();
        }
    
        private void ResetControls()
        { 
            panelControls.Enabled = false;
            txtFind.Text = string.Empty;
            btnSave.Visible = false;
            btnCancel.Visible = false;
            btnDelete.Visible = false;
            NewUSer = false;

            foreach (Control control in this.panelControls.Controls)
            {
                if(control is TextBox)
                    control.Text = "";
                else if (control is GroupBox)
                {
                    foreach (Control checkBox in control.Controls)
                    {
                        CheckBox cb = (CheckBox)checkBox;
                        cb.Checked = false;
                    }
                }
            
            }

        }
        
        private void DeactivateControls()
        {
            panelControls.Enabled = false;
        }

        private void ActivateControls()
        {
            panelControls.Enabled = true;
            btnSave.Visible = true;
            btnCancel.Visible = true;
            btnDelete.Visible = true;
        }

        private void SetUserInfo()
        {
            if (UserInfo.Any())
            {
                foreach (var usert in UserInfo.GetType().GetProperties())
                {
                    foreach (var obj in UserInfo)
                    {
                        if (usert.PropertyType.Name.Equals("Users"))
                        {
                            txtID.Text = obj.GetType().GetProperty("ID").GetValue(obj, null).ToString();
                            txtName.Text = obj.GetType().GetProperty("Nombre").GetValue(obj, null).ToString();
                            txtUser.Text = obj.GetType().GetProperty("Usuario").GetValue(obj, null).ToString();
                            txtPassword.Text = obj.GetType().GetProperty("Contrasena").GetValue(obj, null).ToString();
                            UserRights = obj.GetType().GetProperty("Permisos").GetValue(obj, null).ToString();
                            GetUserRights();
                            ActivateControls();
                        }

                    }
                }
            }
            else 
            {
                ResetControls();
                MessageBox.Show("Usuario No encontrado!" +Environment.NewLine + "Recuerda que es sensible a las Mayusculas","NO ENCONTRADO",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }
        }
 
        private void btnAdd_Click(object sender, EventArgs e)
        {
            ActivateControls();
            GetID();
            btnDelete.Visible = false;
            NewUSer = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ResetControls();
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            int res;
            bool IsNumeric = int.TryParse(txtFind.Text, out res);
                       
            if(IsNumeric)
             UserInfo = BL.GetUserInfo(string.Empty,res);
            else
             UserInfo = BL.GetUserInfo(txtFind.Text);

            SetUserInfo();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (BL.DeleteUserData(Convert.ToInt32(txtID.Text)))
            {
                ResetControls();
                MessageBox.Show("Usuario Eliminado!", "CORRECTO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                MessageBox.Show("Usuario no pudo ser Eliminado!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Users newUser = new Users { ID = Convert.ToInt32(txtID.Text), Nombre = txtName.Text, Usuario = txtUser.Text, Contrasena = txtPassword.Text, Permisos = SumRights().ToString() };


            if (NewUSer)
            {
                if (BL.AddUserData(newUser))
                {
                    ResetControls();
                    MessageBox.Show("Usuario Agregado!", "CORRECTO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                    MessageBox.Show("Usuario no pudo ser Agregado!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
          
            }
            else//update
            {
                if (BL.UpdateUserData(newUser))
                {
                    ResetControls();
                    MessageBox.Show("Usuario Actualizado!", "CORRECTO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                    MessageBox.Show("Usuario no pudo ser Actualizado!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
          
            }
        }

        private void GetUserRights()
        {
            this.chkAdministrador.Checked = HaveRightItem(ItemRights.Administrador);
            this.chkCaja.Checked = HaveRightItem(ItemRights.Caja);
            this.chkCatalogo.Checked = HaveRightItem(ItemRights.Catalogos);
            this.chkReportes.Checked = HaveRightItem(ItemRights.Reportes);
            this.chkComunicados.Checked = HaveRightItem(ItemRights.Comunicados);
        }
        
        private bool HaveRightItem(ItemRights ItemRigth)
        {
            int result = ((int)ItemRigth & Convert.ToInt32(UserRights));
            return result > 0;
        }

        private int SumRights()
        {
            int TotalRights = 0;

            if (this.chkAdministrador.Checked)
                TotalRights += (int)ItemRights.Administrador;
            if (this.chkCaja.Checked)
               TotalRights += (int)ItemRights.Caja;
            if (this.chkCatalogo.Checked)
                TotalRights += (int)ItemRights.Catalogos;
            if (this.chkReportes.Checked)
               TotalRights += (int)ItemRights.Reportes;
            if (this.chkComunicados.Checked)
                TotalRights += (int)ItemRights.Comunicados;

            return TotalRights;
        
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (BL.ExportUsers())
            {
                MessageBox.Show("Usuarios Exportados!", "CORRECTO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
                MessageBox.Show("Usuarios no pudieron ser Exportados!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
          
        }

    }
}
